var g_ani = true;
var g_interval_update = 10000;
var g_interval_ani = 4000;
var g_interval_ani_id = 0;
var gps_map = new Array();// key - value, key=imei, value=Object
var gps_alarm = new Array();
var g_label = null;
var g_control = null;
var g_markerMgr = null;
var g_map = null;
var isSettingAlarm = false;
var alarmUpdateInterval = 10000;
var alarmUpdateIntervalId = 0;
var selectedTrackers = []; // store the imei
var isDragged = false;
var realtimeMapClickListner = null;
var realtiimeMapDragListner = null;
var hostName = window.location.hostname;
var autoFocused = false;// 是否已经自动调焦

function initialize() {
	
	update_tip();
	
    g_map = new GPS_Map("map_canvas", g_default_lat, g_default_lng, g_default_level, g_default_type);
    load_streetnames(g_map);
    realtimeMapClickListner = g_map.addListener("click",
    function(a, b) {
        if (a) {
            for(var i = 0; i < g_uin_array.length; i++) {
                var c = g_uin_array[i];
                if (c == "") {
                    continue;
                }
                var d = gps_map[c];
                if (d == null) {
                    continue;
                }
                if (d.marker == a) {
                    g_seluin = c;
                    update_sel_uin();
                    var e = get_gps_prompt(c, d.id, d.date, d.lat, d.lng, d.signal, d.speed, d.cmd, d.address);
                    d.marker.openInfoWindowHtml(e);
                    break;
                }
            }
        }
    });
    g_map.addListener("drag",
    function() {
        // var a = document.getElementById("target");
        // a.selectedIndex = -1;
        // a.value = "";
    	isDragged = true;
    });
    
    initMap();
    
    window.setTimeout(update_pos); // getpositon_.jsp
    ani_gps();
    getAlarms();
    g_interval_ani_id = setInterval("ani_gps()", g_interval_ani);
    createAlarmMarker();
}


var realtimeTransfering = false;
var initRealtime = false; // 新地图初始化
var isMapInitBefore = false; // 是否初始化过实时地图
function initializeRealtime(country) {
	removeAllInterest();
	realtimeTransfering = true;
	initRealtime = true;
	if(country=='malaysia'){
		g_map = new GPS_Map("realtimeMapDiv", geo_default_lat, geo_default_lng, g_default_level, g_default_type, 'geoserver', country /* malaysia */);
		for(var p in gps_map){
			gps_map[p].marker = false;
			gps_map[p].target_marker = null;
			gps_map[p].lableText = null;
		}
	}else if(country=='nigeria'){
		g_map = new GPS_Map("realtimeMapDiv", geo_default_lat, geo_default_lng, g_default_level, g_default_type, 'geoserver', country /* malaysia */);
		for(var p in gps_map){
			gps_map[p].marker = false;
			gps_map[p].target_marker = null;
			gps_map[p].lableText = null;
		}
	}else if(country == 'kenya'){
		g_map = new GPS_Map("realtimeMapDiv", geo_default_lat, geo_default_lng, g_default_level, g_default_type, 'geoserver', country /* malaysia */);
		for(var p in gps_map){
			gps_map[p].marker = false;
			gps_map[p].target_marker = null;
			gps_map[p].lableText = null;
		}
	}else if(country == 'tanzania'){
		g_map = new GPS_Map("realtimeMapDiv", geo_default_lat, geo_default_lng, g_default_level, g_default_type, 'geoserver', country /* malaysia */);
		for(var p in gps_map){
			gps_map[p].marker = false;
			gps_map[p].target_marker = null;
			gps_map[p].lableText = null;
		}
	}else{	
		g_map = new GPS_Map("realtimeMapDiv", g_default_lat, g_default_lng, g_default_level, g_default_type);
		for(var p in gps_map){
			gps_map[p].marker = false;
			gps_map[p].target_marker = null;
			gps_map[p].lableText = null;
		}
	}
	g_map.currentMapType = 'realtime';
    load_streetnames(g_map);
    realtimeMapClickListner = g_map.addListener("click",
    function(a, b) {
        if (a) {
            for (var i = 0; i < g_uin_array.length; i++) {
                var c = g_uin_array[i];
                if (c == "") {
                    continue;
                }
                var d = gps_map[c];
                if (d == null) {
                    continue;
                }
                /*
				 * if (d.marker == a) { g_seluin = c; update_sel_uin(); var e =
				 * get_gps_prompt(c, d.id, d.date, d.lat, d.lng, d.signal,
				 * d.speed, d.cmd, d.address); d.marker.openInfoWindowHtml(e);
				 * break; }
				 */
            }
        }
    });
    realtiimeMapDragListner = g_map.addListener("drag",
    function() {
    	isDragged = true;
    });
    
    initMap();
    
    ani_gps();
    if(!isMapInitBefore){ // 没有初始化过，则重新设置定时器
    	getAlarms();
    	update_pos();
    // alarmUpdateIntervalId = setInterval(getAlarms, alarmUpdateInterval);
    	g_interval_ani_id = setInterval("ani_gps()", g_interval_ani);
    }
    createAlarmMarker();
    realtimeTransfering = false;
    isMapInitBefore = true;
    currentMap = g_map;
    initInterestPoints();
}

function clearRealtimeData(){
	window.clearInterval(alarmUpdateIntervalId);
	window.clearInterval(g_interval_ani_id);
	g_map.removeListener(null,realtimeMapClickListner);
	g_map.removeListener(null,realtiimeMapDragListner);
}


function getAlarms(){
	Ext.Ajax.request({
	    url: './get_alarming.jsp',
	    params: 'uin='+getOnboardTrackersStr(),
	    success:function(res){
		if(res.status == 404 ||
				res.responseText.indexOf('setLoginInfo') != -1){
			top.location.href = '/';
			return;
		}
			var lines = res.responseText.split("\n");
			var index = 0;
			function procAlarms(){
			    while (index < lines.length) {
			        var j = lines[index];
			        index++;
			        if (j != "") {
			            var k = j.split("=")[0]; // K is IME, tracker user id
			            
			            if (k.match(/^\s*\r*$/)) {
			                continue;
			            }
			            var l = j.split("=")[1];
			            var trackerId = l.split("~")[0];
			            var alarmType = l.split("~")[1];
			            var o = l.split("~")[2];
			            var realTimeDataID = l.split("~")[3];
			            // var p = parse_gprmc(o);
			            var gps = null;
			            // if (p)
			            {
			                if (!isNaN(Number(alarmType)) && Number(alarmType) >0 && Number(alarmType) < 15) {
			                	var hasAlarm = false;
			                	for(var jj = 0; jj < gps_alarm.length; jj++){
			                		if(gps_alarm[jj].realTimeDataID == realTimeDataID){
			                			hasAlarm = true;
			                			break;
			                		}
			                	}
			                	if(!hasAlarm){
			                        var v = new GPSAlarm();
			                        v.gprmc = o;
			                        v.cmd = alarmType;
			                        v.uin = k;
			                        v.realTimeDataID = realTimeDataID;
			                        gps_alarm.push(v);
			                	}
			                }
			            }
			        }
			        var num = 80;
			        if(Ext.isIE6){
			        	num = 40;
			        }
			        if(index>1 && (index % num == 0)){ // 150个的时候休息一下
			        	window.setTimeout(procAlarms, 1000);
			        	return ;
			        }
			    }
			    show_gps_alarm();
			    window.setTimeout(getAlarms, alarmUpdateInterval);
			}
			procAlarms();
	    },
	    failure: function(){
	    	window.setTimeout(getAlarms, alarmUpdateInterval);
	    }

	});
	// window.setTimeout(getAlarms, alarmUpdateInterval);
}

var alarmMarker = null;
function createAlarmMarker(){
    var t = new GPS_Icon();
    t.iconSize = new GPS_Size(20, 20);
    t.iconAnchor = new GPS_Point(10, 10);
    t.shadow = "";
    t.image = "";
    markerOptions = {
        icon: t
    };
    var s = new GPS_LatLng(0, 0);
    // alarmMarker = new GPS_Marker(s, markerOptions);
   // console.log(alarmMarker);
   // g_map.addOverlay(alarmMarker);
}


var g_uin_array = [];// g_uin_str.split(",");
var g_seluin = null;
function ani_gps() {
	
    if (g_ani == false) {
        return;
    }
    for(var i = 0; i < g_uin_array.length; i++) {
        var a = g_uin_array[i];
        
        if (a == "") {
            continue;
        }
        var b = gps_map[a]; // GPS()
        if (b == null) {
            continue;
        }

        if (b.last_lat == 0 && b.last_lng == 0) {
            b.cur_ani++;
            var c = new GPS_LatLng(parseFloat(b.lat), parseFloat(b.lng));
            b.marker.setPoint(c);
            b.target_marker.hide();
        } else if (b.cur_ani < b.ani_count && b.ani_count != 0) {
            if (abs_pos(b.last_lat - b.lat) > 0.003 || abs_pos(b.last_lng - b.lng) > 0.003) {
                b.last_lat = b.lat;
                b.last_lng = b.lng;
                b.cur_ani = b.ani_count;
            }
            b.cur_ani++;
            var d = parseFloat(b.last_lat) + (parseFloat(b.lat) - parseFloat(b.last_lat)) * parseFloat(b.cur_ani) / parseFloat(b.ani_count);
            var e = parseFloat(b.last_lng) + (parseFloat(b.lng) - parseFloat(b.last_lng)) * parseFloat(b.cur_ani) / parseFloat(b.ani_count);
            var pos = new GPS_LatLng(d, e);
            // if(g_bshow_alarm == true){ // 如果已经报警了，就不要设置标签移动了，要不然找不到标签。bug
            	b.marker.setPoint(pos);
            // }
            b.target_marker.show();
            if (a == g_seluin && gps_alarm.length == 0  && isSettingAlarm == false) {  // 如果没有进行移动选择，则可以移动屏幕
                g_map.panTo(pos);
               // document.getElementById("info_prompt").innerHTML = b.cur_ani
				// + " " + d + " " + e + " " + b.last_lat + " " + b.lat + " " +
				// ((parseFloat(b.lat) - parseFloat(b.last_lat)))
            }
        }
        if (b.last_lat == b.lat && b.last_lng == b.lng || b.last_lat == 0 && b.last_lng == 0) {
            b.target_marker.hide();
        }
    }
   
    
}
var g_bshow_alarm = false;
function close_gps_alarm() {
    if (gps_alarm.length > 0) {
        gps_alarm.shift();
    }
    document.getElementById("wav_alert").src = "";
// show_gps_alarm()
    g_bshow_alarm = false;    
}

function isAlarmInserted(alarm){
	
	for(var i = 0; i < insertedAlarms.length; i++){
// console.log(insertedAlarms[i].realTimeDataID, alarm.realTimeDataID);
		if(insertedAlarms[i].realTimeDataID 
				== alarm.realTimeDataID){
			return true;
		}
	}	
	return false;
}

var insertedAlarms = [];
function show_gps_alarm() {
	
	var insertedNew = false;
    if (gps_alarm.length <= 0) {
        return;
    }
    
    for(var i = 0 ; i < gps_alarm.length; i++){  
	    var alarm = gps_alarm[i]; // GPSAlarm()
	   
	    if(isAlarmInserted(alarm)){
	    	continue;
	    }
	    if(alarm.cmd == 11 || alarm.cmd == 13){ // ACC状态和Door状态不是报警,不用显示在弹出框
	    	insertedAlarms.push(alarm);
	    	continue;
	    }
	    
	    var b = alarm.uin;
	    if (b == "") {
	    	continue;
	    }
	    var c = gps_map[b]; // GPS()
	    if (c == null) {
	    	continue;
	    }
	    var d = parse_gprmc(alarm.gprmc);
	    
	    // var e = get_gps_prompt(b, d['id'], d['date'], d['lat'], d['lng'],
		// d['signal'], d['speed'], a.cmd, "");
	    var e = get_prompt_data(b, d['id'], d['date']+" "+d['time'], d['lat'], d['lng'], d['signal'], d['speed'], alarm.cmd, alarm.realTimeDataID);
	    
	    var f = new GPS_LatLng(parseFloat(d['lat']), parseFloat(d['lng']));
	    
	    
	    	insertPromptRow(e);
	    	insertedAlarms.push(alarm);
	    	insertedNew = true;
    }

    
    gps_alarm = [];
    if(insertedNew){
    	window.setTimeout('showAlarmPrompt()', 3000);
    	document.getElementById("wav_alert").src = "images/alarm.wav";    
    }
    
    
    // g_map.panTo(f);
    // window.focus();

// if (g_bshow_alarm == true) {
// return
// }
    
// if (alarmMarker) {
// alarmMarker.setPoint(f);
// g_bshow_alarm = true;
// alarmMarker.alert(e,
// function() {
// close_gps_alarm()
// })
// } else {
// close_gps_alarm()
// }
}
var test_index = 0;
function onDataCome(html, f) {  // getPosition.jsp
    // document.getElementById("info_prompt").innerHTML = html.replace(/\n/g,
	// "<br>");
    var signal = false;
    var lines = html.split("\n");
    var showMutilTrackers = true;// document.getElementById("showMutilTrackers").checked;
    var now = (new Date()).getTime();
    var index = 0;
    function processData(){
	    while (index < lines.length) {
	        var j = lines[index];
	        index++;
	        try{
		        if (j != "") {
		            var k = j.split("=")[0]; // K is IME, tracker user id
		            
		            if (k.match(/^\s*\r*$/)) {
		                continue;
		            }
		            var grms = j.split("=")[1];
		            var infos = grms.split("~");
		            var trackerId = infos[0];
		            var alarmType = infos[1];
		            var o = infos[2];
		            var realTimeDataId = infos[3];
		            var address = infos[4];
		            var p = parse_gprmc(o);
		            var gps = null;
		            
		            if (p) {
		                if (p['signal'] == 0) {
		                    ;
		                }
		                
		                if (gps_map[k] != null) {
		                    gps = gps_map[k];
		                } else {
		                	gps = new GPS();
		                    gps_map[k] = gps;
		                }
		                
		                gps.signal = p['signal'];
		                
		                if (!isNaN(f) && f == 1) {
		                    gps.signal = 0;
		                }
		                gps.id = trackerId;
		                if (j == gps.src) {
		// console.log("j:",j);
		// gps.same_times++;
		// if (gps.same_times >= 6 * 5) {
		// gps.signal = 0;
		// }
		                } else {
		                    gps.cur_ani = 0;
		                    gps.src = j;
		                    gps.same_times = 0;
		                    if (gps.update_interval == 0) {
		                        gps.ani_count = 0;
		                    } else {
		                        var r = new Date();
		                        gps.ani_count = (r.getTime() - gps.update_interval) / g_interval_ani;
		                        gps.update_interval = r.getTime();
		                    }
		                }
		                gps.last_lat = gps.lat;
		                gps.last_lng = gps.lng;
		                gps.uin = k;
		                gps.lat = p['lat'];
		                gps.lng = p['lng'];
		                gps.date = p['date'];
		                gps.speed = p['speed'];
		                gps.direction = p['direction'];
		                gps.time = p['time'];
		                gps.date = p['date'];
		                gps.acc = p['acc'];
		                gps.door = p['door'];
		                gps.cmd = alarmType;
		                gps.address = address;
		                if (g_seluin == null) {
			                g_seluin = k; // The selected tracker
			                try{
			                	trackersGrid.getSelectionModel().selectRow(gpstracker_map[g_seluin].rowIndex);
			                }catch(exxx){
			                	if(typeof console != undefined){
			    	        		console.log("selection error....", exxx);
			    	        	}
			                }
			            }
		            }
		            var pos = new GPS_LatLng(parseFloat(gps.lat), parseFloat(gps.lng));
		            if(gps.signal == 1){
		            	setHighLightOnLeftGrid(gps.uin);// 在左边列表突出
		            }else{
		            	setNormalOnLeftGrid(gps.uin); // 在左边列表不突出
		            }
		            if (gps.marker) {
		                // q.marker.setImage(get_arrow_img(q.direction,
						// q.signal, q.cmd))
		            	if(gps.signal == '1'){ // 'images/car2.png'
		            		// gps.target_marker.setImage(getOnlineIcon(gpstracker_map[k]));
							// //在线显示的车
		            		gps.target_marker.setImage(getOnlineIcon(gpstracker_map[k],gps.direction)); // 在线显示的车
		            		// searchimg(getOnlineIcon(gpstracker_map[k]));
		            	}else{ // 'images/car1_gray.png'
		            		gps.target_marker.setImage(getOfflineIcon(gpstracker_map[k]));
		            	} 
		            } else {
		                var t = new GPS_Icon();
		                t.iconSize = getIconSize(gpstracker_map[k]); // new
																		// GPS_Size(32,
																		// 16)
		                t.iconAnchor = new GPS_Point(11, 25);
		                t.shadow = "";
		                t.image = getOfflineIcon(gpstracker_map[k]);// "images/car1_gray.png";
		                markerOptions = {
		                    icon: t
		                };
		                gps.tracker = gpstracker_map[k]; 
		                gps.target_marker = new GPS_Marker(pos,{title: (gpstracker_map[k] ? gpstracker_map[k].trackerName : ''), uin:k, icon:t}, g_map.map);// new
																																							// GPS_Marker(s,
																																							// markerOptions);
		                
		                gps.target_marker.gps = gps;
		                g_map.addOverlay(gps.target_marker);
		                gps.target_marker.addListener("click",function(marker, lat1, lng1){
		                	g_seluin = marker.uin;
		                	update_sel_uin(true);
		                	var g_marker_prompt = get_prompt_on_map(marker.gps.uin, marker.gps.id, marker.gps.date, marker.gps.lat, marker.gps.lng, marker.gps.signal, marker.gps.speed, marker.gps.cmd, marker.gps.time);
		                	marker.openInfoWindowHtml(g_marker_prompt, {maxWidth:130, onCloseFn:function(){
		                		marker.openInfo = false;
		        	        }, lat:lat1, lng:lng1});
		                	marker.openInfo = true;
		                });
		                
		                
		                
		                t = new GPS_Icon();
		                t.iconSize = new GPS_Size(20, 20);
		                t.iconAnchor = new GPS_Point(10, 10);
		                t.shadow = "";
		                // t.image = get_arrow_img(q.direction, q.signal,
						// q.cmd);
		                markerOptions = {
		                    icon: t
		                };
		                gps.marker = true;// new GPS_Marker(pos);//new
											// GPS_Marker(s, markerOptions);
		                
		                var lt = new GPS_Label(new GPS_LatLng(g_default_lat, g_default_lng), currentMap.map);
		                gps.lableText = lt;
		                g_map.addLabel(lt);
		                
		                // g_map.addOverlay(q.marker)
		            }
		            
		            
		            // console.log("fdfd fd:",gps.lat,gps.last_lat, gps.points);
		            if(gps.last_lng != gps.lng || gps.last_lat != gps.lat){
		            	if(gps.lineStarted == null){
		            		gps.lineStarted = now;
		            	}else if(hostName.indexOf("gktracking") == -1){ // www.gktracking.com
																		// 这个域名不清除连线
		            		if(now - gps.lineStarted > 5*60*1000){ // 每5分钟清一次连线
		            			gps.points = [];
		            			gps.lineStarted = now;
		            		}
		            	}
		            	gps.points.push(pos);
		            	if(gps.line != null)
		            		g_map.removePolyline(gps.line);
		            	gps.line = null;
		            }
		            
		            if (g_ani == false) {
		                // q.marker.setPoint(s)
		            }
		            
		            if(selectedTrackers.length == 0 && prevSelectedIMEI.length > 0){
		            	g_seluin = prevSelectedIMEI[0];
		            }
		           // console.log('selectedTrackers=',selectedTrackers,'
					// prevSelectedIMEI=',prevSelectedIMEI,
		           // ' k=',k,' 0=',trackerStore.getAt(0).data.uin);
		            if(selectedTrackers.indexOf(k) > -1 ||
		            		prevSelectedIMEI.indexOf(k) > -1){
		            	gps.target_marker.setPoint(pos);
		            	gps.target_marker.show();
		            	gps.lableText.showMe();
		            	if(gps.target_marker.openInfo === true){
		            		var g_marker_prompt = get_prompt_on_map(gps.uin, gps.id, gps.date, gps.lat, gps.lng, gps.signal, gps.speed, gps.cmd, gps.time);
		            		var showGps = gps; // avoid override
		            		gps.target_marker.openInfoWindowHtml(g_marker_prompt, {maxWidth:130, onCloseFn:function(){
		            			showGps.target_marker.openInfo = false;
		        	        }, zoomLevel:g_map.getZoom(), lat:pos.lat(), lng:pos.lng()});
		            		gps.target_marker.openInfo = true;
		            	}
		            	if(gps.line == null){
		            		// console.log(gps.line,gps.points);
		            		gps.line = new GPS_Polyline(gps.points, "#FF0000", 3, gps.uin);
		            		g_map.addPolyline(gps.line);
		            	}
		            	gps.lableText.put_text(gpstracker_map[gps.uin]  ? gpstracker_map[gps.uin].trackerName:"");
		            	gps.lableText.move(pos);
		            }else if((selectedTrackers.length == 0 && prevSelectedIMEI.length==0 && 
		            		trackerStore.getAt(0).data.uin != k)
		            		|| selectedTrackers.length > 0 || prevSelectedIMEI.length>0){
		            	gps.target_marker.hide();
		            	gps.lableText.hideMe();
		            	if(gps.target_marker.popup){
		            		gps.target_marker.popup.destroy();
		            		gps.target_marker.popup = null;
		            	}
		            	if(gps.line != null)
		            		g_map.removePolyline(gps.line);
		            	gps.line = null;
		            }
		            
		            if (!isNaN(Number(alarmType)) && Number(alarmType) >0 && Number(alarmType) < 15) {
		// if (!isNaN(f) && f == 1) {
		// g = false
		// } else {
		                    var v = new GPSAlarm();
		                    v.gprmc = o;
		                    v.cmd = alarmType;
		                    v.uin = k;
		                    // gps_alarm.push(v);
		                    signal = true;
		// }
		            }
		// console.log("q.lat:"+q.lat," q.lng:"+q.lng);
		            getOneTrackerAddress(gps);
		        } // explain a line text.
	        }catch(exline){
	        	if(typeof console != undefined){
	        		console.log("parse geo line text...", exline);
	        	}
	        }
	        var num = 80;
	        if(Ext.isIE6){
	        	num = 40;
	        }
	        if(index > 1 && (index % num == 0)){
	        	window.setTimeout(processData, 1000);
	        	return;
	        }
	    } // End of command lines. parsing
	    // show_tip("");
	    update_sel_uin();
	    if (gps_alarm.length > 0) {
	        show_gps_alarm();
	    }
	    
	    
	    
	    
	    window.setTimeout("update_pos()", 4000);
    }
    processData();
}


var degreeToRotate=0;
function searchimg(imgsrc)
{
var imglist=document.getElementsByTagName('img');
for(var i=0;i<imglist.length;i++)
{
 if(imglist[i].src.indexOf(imgsrc)>0)
 {
  // alert(imglist[i]+'-'+i);
 // var imageToRotate =imglist[i];
 // rotateImage(imglist[i]);
 imageToRotate.style.filter="progid:DXImageTransform.Microsoft.Matrix(sizingMethod='auto expand')";
 var deg2radians =600/360;
degreeToRotate++; 
degreeToRotate=degreeToRotate%360;  
rad = degreeToRotate * deg2radians ; 
costheta = Math.cos(rad); 
sintheta = Math.sin(rad); 
imageToRotate.filters.item(0).M11 = costheta; 
imageToRotate.filters.item(0).M12 = -sintheta; 
imageToRotate.filters.item(0).M21 = sintheta; 
imageToRotate.filters.item(0).M22 = costheta;
break;
 }
}
}

function getOnlineIcon_back(tracker){
return 'images/arrow_green_small.png';
	if(tracker.model == 'car'){
		return 'images/car2.png';
	}else if(tracker.model == 'truck'){
		return 'images/truck.png';
	}else if(tracker.model == 'trailer'){
		return 'images/trailer.png';
	}else if(tracker.model == 'schoolbus'){
		return 'images/schoolbus.png';
	}else if(tracker.model == 'policecar'){
		return 'images/policecar.png';
	}else if(tracker.model == 'human'){
		return 'images/human.gif';
	}else if(tracker.model == 'motorcycle'){
		return 'images/motorcycle.gif';
	}else if(tracker.model == 'boat'){
		return 'images/boat.gif';
	}else if(tracker.model == 'ambulance'){
		return 'images/ambulance.gif';
	}else if(tracker.model == 'pickup'){
		return 'images/pickup.png';
	}else if(tracker.model == 'jeep'){
		return 'images/jeep.png';
	}else if(tracker.model && tracker.model.indexOf(".") > -1){
		return "images/trackericon/"  + tracker.model;
	}
	return 'openLayers/customer/point_icon.png';
}


function getOnlineIcon(tracker,direction_){
var direction_v=parseInt(direction_);

if((direction_v>=335&&direction_v<=360)||(direction_v>=0&&direction_v<=25))
{
return 'images/arrow_green0.png';
}else if(direction_v>=26&&direction_v<=70)
{
return 'images/arrow_green45.png';
}
else if(direction_v>=71&&direction_v<=115)
{
return 'images/arrow_green90.png';
}
else if(direction_v>=116&&direction_v<=160)
{
return 'images/arrow_green135.png';
}
else if(direction_v>=161&&direction_v<=205)
{
return 'images/arrow_green180.png';
}
else if(direction_v>=206&&direction_v<=250)
{
return 'images/arrow_green225.png';
}
else if(direction_v>=251&&direction_v<=295)
{
return 'images/arrow_green270.png';
}
else if(direction_v>=296&&direction_v<=340)
{
return 'images/arrow_green315.png';
}

}

function getOfflineIcon(tracker){
// return 'images/arrow_gray_small.png';
	if(tracker.model == 'car'){
		return 'images/car1_gray.png';
	}else if(tracker.model == 'truck'){
		return 'images/truck2.png';
	}else if(tracker.model == 'trailer'){
		return 'images/trailer2.png';
	}else if(tracker.model == 'schoolbus'){
		return 'images/schoolbus2.png';
	}else if(tracker.model == 'policecar'){
		return 'images/policecar2.png';
	}else if(tracker.model == 'human'){
		return 'images/human2.gif';
	}else if(tracker.model == 'motorcycle'){
		return 'images/motorcycle2.png';
	}else if(tracker.model == 'boat'){
		return 'images/boat2.png';
	}else if(tracker.model == 'ambulance'){
		return 'images/ambulance2.png';
	}else if(tracker.model == 'pickup'){
		return 'images/pickup2.png';
	}else if(tracker.model == 'jeep'){
		return 'images/jeep2.png';
	}else if(tracker.model && tracker.model.indexOf(".") > -1){
		return "images/trackericon/off/"  + tracker.model;
	}
	return 'openLayers/customer/point_icon2.png';
}

function getIconSize(tracker){ // new GPS_Size(32, 16)
return new GPS_Size(30,20);
	if(tracker.model == 'car'){
		return new GPS_Size(32, 16);
	}else if(tracker.model == 'truck'){
		return new GPS_Size(32, 25);
	}else if(tracker.model == 'trailer'){
		return new GPS_Size(32, 20);
	}else if(tracker.model == 'schoolbus'){
		return new GPS_Size(32, 26);
	}else if(tracker.model == 'policecar'){
		return new GPS_Size(32, 21);
	}else if(tracker.model == 'human'){
		return new GPS_Size(14, 32);
	}else if(tracker.model == 'motorcycle'){
		return new GPS_Size(32, 21);
	}else if(tracker.model == 'boat'){
		return new GPS_Size(32, 16);
	}else if(tracker.model == 'ambulance'){
		return new GPS_Size(32, 16);
	}else if(tracker.model == 'jeep'){
		return new GPS_Size(32, 17);
	}else if(tracker.model == 'pickup'){
		return new GPS_Size(32, 11);
	}else if(tracker.model && tracker.model.indexOf(".") > -1){
		return new GPS_Size(48, 48);
	}
	
	return new GPS_Size(20, 33);
}


function getOneTrackerAddress(gps){
	if(gps.address != ''){
		return;
	}
	get_address(gps.lat, gps.lng,
            function(a, b, c) {
            	if(isNaN(a) || isNaN(b)){
            		return;
            	}
            	for (var d in gps_map) {
                    var q = gps_map[d];// GPS()
                    if (Math.abs(parseFloat(q.lat) - parseFloat(a)) < 0.0001 && Math.abs(parseFloat(q.lng) - parseFloat(b)) < 0.0001) {
                   	// console.log("address:",c," lat:"+a,"
					// lng:"+b,'q.lat:',q.lat,'q.lng',q.lng);
                        q.address = c;
                        if(d == g_seluin){
                        	document.getElementById("info_address").innerHTML = c;
// g_label.put_text(c);
// var pos = new GPS_LatLng(parseFloat(a), parseFloat(b));
// g_label.move(pos);
                        }
                        // console.log('set address',d, ' select :',g_seluin);
                        
                    }
                }
            }, gps.id);
}

function update_pos() {
    var c = "get_position.jsp";// 返回所有tracker的位置
// GPS_DownloadUrl(c,
// function(a, b) {
// onDataCome(a, 0);
// });
    Ext.Ajax.request({
	    url: c,
	    method:'POST',
	    params: "uin=" + getOnboardTrackersStr(true) +"&timestamp="+(new Date()).getTime(),
	    success:function(res){
    	if(res.status == 404 ||
		    res.responseText.indexOf('setLoginInfo') != -1){
			top.location.href = '/';
			return;
		}
    	try{
    		onDataCome(res.responseText, 0);
    	}catch(e){
    		if(typeof console != undefined){
    			try{
    				console.log(e);
    			}catch(e1){}
    		}
    	}
    	},
	    failure: function(){
    		window.setTimeout("update_pos()", 4000);
	    }
    });
}

function update_mileage(mileage) {
    var c = "get_position.jsp";//
// GPS_DownloadUrl(c,
// function(a, b) {
// onDataCome(a, 0);
// });
    Ext.Ajax.request({
	    url: c,
	    method:'POST',
	    params: "uin=" + getOnboardTrackersStr(true)+"&trackId="+gpstracker_map[g_seluin].trackerId+"&mileage="+mileage+"+&timestamp="+(new Date()).getTime(),
	    success:function(res){
    	if(res.status == 404 ||
		    res.responseText.indexOf('setLoginInfo') != -1){
			top.location.href = '/';
			return;
		}
    	document.getElementById("info_mileage").innerHTML =mileage+"KM";
    	// succ
    	},
	    failure: function(){
	    	document.getElementById("info_mileage").innerHTML =mileage+"KM";
	    	// Ext.Msg.alert('Confirm', ' Modification fails! ');
    		// window.setTimeout("update_pos()", 4000);
	    }
    });
}

var prevSelectedIMEI = [];
function getOnboardTrackersStr(isPos /* 是否位置请求 */){
	prevSelectedIMEI = [];
	var text = '';
	for(var p in gpstracker_map){
		text = text + p +",";
	}
	if(previousSelections != null && previousSelections.getCount() > 0){
		for(var i = 0; i < previousSelections.getCount(); i++){
			var data = previousSelections.get(i);
			text = text + data.uin+",";
			prevSelectedIMEI.push(data.uin);
		}
	}
	if(text.lastIndexOf(",") == text.length - 1){
		text = text.substring(0, text.length - 1);
	}
	if(initRealtime && isPos){
		initRealtime = false;
		text = text + "&isRenew=true";
	}
	return text;
}

function initMap() {
// g_label = new GPS_Label(new GPS_LatLng(g_default_lat, g_default_lng));
// g_map.addLabel(g_label);
    /*
	 * var a = new GPS_Control(g_map); g_map.addControl(a); var b =
	 * document.getElementById("control_area").innerHTML; a.put_content(b);
	 * document.getElementById("map_canvas").focus()
	 */
}

function onDeSelTargetChange(uin){
	try{
		if(gps_map[uin]){
	    	if(gps_map[uin].target_marker == null){
	    		return;
	    	}
	    	gps_map[uin].target_marker.hide();
	    	gps_map[uin].lableText.hideMe();
	    }
	}catch(e){
		
	}
	
}

function onSelTargetChange(uin) {
    // var a = document.getElementById("target");
	isDragged = false;
	if(gps_map[g_seluin]){
		/*
		 * if(gps_map[g_seluin].target_marker){
		 * gps_map[g_seluin].target_marker.hide(); }
		 * if(gps_map[g_seluin].lableText){
		 * gps_map[g_seluin].lableText.hideMe(); }
		 */
	}
	g_seluin = uin;
    isSettingAlarm = false;
    update_sel_uin(true);
}
function update_sel_uin(a) {
    var b = "<font color=red>" + g_str_no_data + "</font>";
    if (g_seluin == "") {
        b = "";
    }
    try{
    document.getElementById("info_title").innerHTML = gpstracker_map[g_seluin]?gpstracker_map[g_seluin].trackerName:"";
    document.getElementById("info_time").innerHTML = b;
    document.getElementById("info_lat").innerHTML = b;
    document.getElementById("info_lng").innerHTML = b;
// document.getElementById("info_signal").innerHTML = b == "1" ? "ok":"no";
    document.getElementById("info_speed").innerHTML = "0";
    }catch(e){}
 // document.getElementById("info_direction").innerHTML = "-1";
// document.getElementById("info_state").innerHTML = b;
// document.getElementById("info_comment").innerHTML = "";
    var c = gps_map[g_seluin];  // GPS()
    // console.log('selected uin',g_seluin);
    if (c == null) {
    	try{
        document.getElementById("info_address").innerHTML = "";
    	}catch(e){}
        setDefaultSignalTip();
        return;
    }
    if(gps_map[g_seluin]){
    	if(gps_map[g_seluin].target_marker == null){
    		return;
    	}
    	gps_map[g_seluin].target_marker.show();
    }
    
    var d = new GPS_LatLng(parseFloat(c.lat), parseFloat(c.lng));
// if ((g_ani == false || a == true || c.last_lat == 0) && gps_alarm.length ==
// 0) {
// g_map.panTo(d)
// }
    if(gps_map[g_seluin].target_marker){
    	gps_map[g_seluin].target_marker.setPoint(d);
    }
    if(!isDragged)
    	g_map.panTo(d);
    if(!autoFocused){
    	g_map.setZoom(focusLevel);
    	autoFocused = true;
    }
    var e = c.id;
    var f = c.src.split("=")[1].split("~")[2];
    var g = parse_gprmc(f);
    document.getElementById("info_time").innerHTML = g["time"];
    document.getElementById("info_date").innerHTML = g["date"];
    document.getElementById("info_lat").innerHTML = g["lat"];
    document.getElementById("info_lng").innerHTML = g["lng"];
    // document.getElementById("info_signal").innerHTML = g["signal"] == "1" ?
	// "ok":"no";
    document.getElementById("info_speed").innerHTML = g["speed"];
    // document.getElementById("info_direction").innerHTML = g["direction"];
    document.getElementById("info_acc").innerHTML = (g['acc'] == 1 ? acc_on: acc_off);
    document.getElementById("info_door").innerHTML = (g['door'] == 1 ? door_opened: door_closed);
    document.getElementById("info_address").innerHTML = c.address;
    document.getElementById("info_mileage").innerHTML = g["mileage"]+"KM";
    
    gps_MapLeftinfo(f);
    
    c.lableText.showMe();
    c.lableText.put_text(gpstracker_map[g_seluin]  ? gpstracker_map[g_seluin].trackerName:"");
    c.lableText.move(d);
    if (c.cmd > 0) {
        // document.getElementById("info_state").innerHTML = '<blink id=tm
		// begin="0;tm.end+0.4" dur=0.6><span
		// style="color:red;font-weight:bold">' + get_gps_cmd_str(c.cmd) +
		// '</span></blink>'
    } else {
        // document.getElementById("info_state").innerHTML =
		// get_gps_cmd_str(c.cmd)
    }
    if (e > 0) {
        var h = '<a href="#" onclick="';
        h += "javascript:window.parent.showPopWin('gps_comment.jsp?id=" + e + "', 400, 300)";
        h += '">' + g_str_comment + '</a>';
        document.getElementById("info_comment").innerHTML = h;
    }
    if(g["signal"] == "1"){
    	// document.getElementById("signalImg").src = "arrow/signal.gif";
    	// document.getElementById("offlineText").style.display="none";
    	// document.getElementById("onlineText").style.display="";
    }else{
    	// document.getElementById("signalImg").src = "arrow/nosignal.gif";
    	// document.getElementById("offlineText").style.display="";
    	// document.getElementById("onlineText").style.display="none";
    }
    if(c.cmd == "0"){
    	document.getElementById("alarmImg").src = "arrow/noalarm.gif";
    	document.getElementById("noalarmText").style.display="";
    	document.getElementById("alarmText").style.display="none";
    }else{
    	document.getElementById("alarmImg").src = "arrow/alarm.gif";
    	document.getElementById("noalarmText").style.display="none";
    	document.getElementById("alarmText").style.display="";   	
    }
}

function gps_MapLeftinfo(obj)
{
	if(obj!=null&&obj.length>0)
		{
		
		var g2=parse_gprmc_mao(obj);
		if(g2['battery'].length>0&&g2['battery']!='null')
			{
			document.getElementById('onlineTracker_Battery').innerHTML=g2['battery']+'&nbsp;%';
			}else
				{
				document.getElementById('onlineTracker_Battery').innerHTML='None';		
				}
		
		if(g2['fuel'].length>0&&g2['fuel']!='null')
		{
		document.getElementById('onlineTracker_Fuel').innerHTML=g2['fuel']+'&nbsp;V';
		}else
			{
			document.getElementById('onlineTracker_Fuel').innerHTML='None';		
			}
		if(g2['voltage'].length>0&&g2['voltage']!='null')
		{
		document.getElementById('onlineTracker_Power').innerHTML=g2['voltage']+'&nbsp;V';
		}else
			{
			document.getElementById('onlineTracker_Power').innerHTML='None';		
			}
		if(g2['ad2'].length>0&&g2['ad2']!='null')
		{
		document.getElementById('onlineTracker_AD2').innerHTML=g2['ad2']+'&nbsp;V';
		}else
			{
			document.getElementById('onlineTracker_AD2').innerHTML='None';		
			}
		
		if(g2['direction'].length>0&&g2['direction']!='null')
		{
		document.getElementById('onlineTracker_Direction').innerHTML=g2['direction']+'&nbsp;';
		}else
			{
			document.getElementById('onlineTracker_Direction').innerHTML='None';		
			}
			
		if(g2['flag']!=null&&g2['flag']!='null'&&g2['flag'].length>=0)
		{
		var flags=g2['flag'];
		if(flags.length==0)
		{
		 flags="000000";
		}
		if(flags.length==1)
		{
		 flags="00000"+flags;
		}
		if(flags.length==2)
		{
		 flags="0000"+flags;
		}
		if(flags.length==3)
		{
		 flags="000"+flags;
		}
		if(flags.length==4)
		{
		 flags="00"+flags;
		}
		if(flags.length==5)
		{
		 flags="0"+flags;
		}
//var by=dec2bin(flags.substring(5,6)).substring(2,4);
// by=by=='00'?'No Signal':by=='01'?'GPS':'GSM';
////alert(tem);

//var modu=dec2bin(flags.substring(5,6)).substring(0,2);
// modu=modu=='00'?'Normal':by=='01'?'Module Faulty':'Ant Faulty';

var by=to_16(flags.substring(5,6)).substring(2,4);
 by=by=='00'?'No Signal':by=='01'?'GPS':'GSM';
var modu=to_16(flags.substring(5,6)).substring(0,2);
 modu=modu=='00'?'Normal':by=='01'?'Module Faulty':'Ant Faulty';
 
//alert(tem2);
var gsm=parseInt((flags).substring(0,2),16);

var bit2=to_16(flags.substring(4,5));
var acc=bit2.substring(3,4);
acc=acc=='1'?'on':'off';

var door=bit2.substring(2,3);
door=door=='1'?'open':'close';

var sos=bit2.substring(1,2);
sos=sos=='1'?'Yes':'No';

var over=bit2.substring(0,1);
over=over=='1'?'Yes':'No';

var bit3=to_16(flags.substring(3,4));
var inpu=bit3.substring(2,3);
inpu=inpu=='1'?'Yes':'No';

var Engine=bit3.substring(1,2);
Engine=Engine=='1'?'On':'Off';

var output=bit3.substring(0,1);
output=output=='1'?'1':'0';
		
		
		document.getElementById('onlineTracker_Located').innerHTML=by;
		document.getElementById('onlineTracker_GPS').innerHTML=modu;
		document.getElementById('onlineTracker_GSM').innerHTML=gsm;
		document.getElementById('onlineTracker_SOS').innerHTML=sos;
		document.getElementById('onlineTracker_Overspeed').innerHTML=over;
		document.getElementById('onlineTracker_Input').innerHTML=inpu;
		document.getElementById('onlineTracker_Engine').innerHTML=Engine;
		document.getElementById('onlineTracker_Output').innerHTML=output;
		
	    
	    }else
	    {
	    
	    document.getElementById('onlineTracker_Located').innerHTML='None';
		document.getElementById('onlineTracker_GPS').innerHTML='None';
		document.getElementById('onlineTracker_GSM').innerHTML='None';
		document.getElementById('onlineTracker_SOS').innerHTML='None';
		document.getElementById('onlineTracker_Overspeed').innerHTML='None';
		document.getElementById('onlineTracker_Input').innerHTML='None';
		document.getElementById('onlineTracker_Engine').innerHTML='None';
		document.getElementById('onlineTracker_Output').innerHTML='None';
	    
	    }
		
		
		}
}

//十进制转换2进制
  function dec2bin(val){
  //dec = document.F.DEC.value;
  dec = val;
  bin = "";
  while (dec > 0) {
  if (dec%2 != 0) { bin = "1" + bin; }
  else { bin = "0" + bin; }
  dec = parseInt(dec/2);
  }
  //document.F.BIN.value = bin;
  if(bin.length==0)
  {
   bin="0000";
  }
  if(bin.length==1)
  {
   bin="000"+bin;
  }
  if(bin.length==2)
  {
   bin="00"+bin;
  }
  if(bin.length==3)
  {
   bin="0"+bin;
  }
  return bin;
  
  }
  //十六进制转换二进制
  function to_16(val)
  {
  
  var bin=(parseInt(val,16).toString(2));
  if(bin.length==1)
  {
   bin="000"+bin;
  }
  if(bin.length==2)
  {
   bin="00"+bin;
  }
  if(bin.length==3)
  {
   bin="0"+bin;
  }
  return bin;

  }

function setDefaultSignalTip(){
	try{
   	document.getElementById("signalImg").src = "arrow/nosignal.gif";
	document.getElementById("offlineText").style.display="";
	document.getElementById("onlineText").style.display="none";

	document.getElementById("alarmImg").src = "arrow/noalarm.gif";
	document.getElementById("noalarmText").style.display="";
	document.getElementById("alarmText").style.display="none";
	}catch(e){}
}

function update_tip() {
    var c = "gps_tip.jsp";
    GPS_DownloadUrl(c,
    function(a, b) {
        document.getElementById("tip").innerHTML = a;
        setTimeout("update_tip()", 5000);
    });
}

function reLoadPage(a) {}
function DoControl(a /* control name */, w , h) {
    var b = gpstracker_map[g_seluin];
    
    if (b == null) {
        alert(g_str_select_tracker);
        return
    }
    var c = "controls/"+a+"?";
    c += "plugin=" + encodeURI(b.plugin);
// c += "&type=" + encodeURI(a);
    c += "&uin=" + encodeURI(b.uin);// userTrackerId
    c += "&name=" + encodeURI(b.name);
    c += "&model=" + encodeURI(b.model);
    c += "&trackerId=" + encodeURI(b.trackerId);
    if(w == null){
    	w = 350;
    }
    if(h == null){
    	h = 250;
    }
    showPopWin(c, w, h);
}

// the event handler function for geo map.
var geoCreated = function(){};
var geoModify = function(){};
var geoDone = function(){};

function selectRangeOnMap(g,data_value) {
	var geoSelectCallBack = null;
	var geoPoints = [];
	var geoMarkers = [];
	isSettingAlarm = true; // 限定了地图不能自动移动
	isDragged = true;
	geoSelectCallBack = g;
	var oldLine = null;
	var dashLine = null;
	
	var win = null;
	function showOKDialog(){ // dialog to finish editting.
		if(win == null){
	    	var button = new Ext.Button({type:'button', 
				text:'YES',split: false,width:100,
				enableToggle:false});
				
				button.on('click',function(){
					var data = '';
					for(var i=0; i < geoPoints.length; i++){
						if(i > 0){
							data = data+";";
						}
						data = data + geoPoints[i].lng().toFixed(6)+","+geoPoints[i].lat().toFixed(6);
					}
					isDragged = false;
					isSettingAlarm = false;
					geoSelectCallBack(data);
					win.destroy();
					g_map.removePolygon(oldLine);
					removeDragPoints();
				});
				
				var buttonNO = new Ext.Button({type:'button', 
					text:'NO',split: false,width:100,
					enableToggle:false});
				   buttonNO.on('click',function(){
						var data = '';
						isDragged = false;
						isSettingAlarm = false;
						geoSelectCallBack(data);
						win.destroy();
						g_map.removePolygon(oldLine);
						removeDragPoints();
					});
				
	    	win = new Ext.Window({html: finishGEOEdit,closable:false,
	    		width:300,
	            height:100,
	            plain:true,
	            border:false,
	            buttons:[button,buttonNO],
	            bodyCssClass:'gps-window-body',
	            x:200,
	            y:100
	    		});
	    	win.show();
	    }
	}
	
	var removeDragPoints = function(){
		if(geoMarkers.length > 0){
			for(var i=0; i < geoMarkers.length; i++){
				g_map.removeOverlay(geoMarkers[i]);
			}
			geoMarkers = [];
		}
	};
	
	var removeMiddlePoints = function(){
		if(geoMarkers.length > 0){
			var rindex = [];
			for(var i=0; i < geoMarkers.length; i++){
				if(!geoMarkers[i].isCorner){
					g_map.removeOverlay(geoMarkers[i]);
					rindex.push(i);
				}
			}
			for(var i=0; i < rindex.length; i++){
				geoMarkers.splice(rindex[i], 1);
			}
		}
	};
	
	var caculateMiddleDragPoints=function(){ // caculate and reposition
		if(geoMarkers.length > 0){
			for(var i=0; i < geoMarkers.length; i++){
				if(!geoMarkers[i].isCorner){
					var m = geoMarkers[i];
					var prev = geoPoints[m.prevIndex];
					var cur = geoPoints[m.curIndex];
					var pos = new GPS_LatLng(prev.lat()+(cur.lat()-prev.lat())/2, prev.lng()+(cur.lng()-prev.lng())/2);
					geoMarkers[i].setPoint(pos);
				}
			}
		}
	};
	var setAlphaDragPoints=function(points){
		for(var i=1; i < points.length; i++){// add a drag point for every
												// borderline
			var prev = points[i-1];
			var cur = points[i];
			var pos = new GPS_LatLng(prev.lat()+(cur.lat()-prev.lat())/2, prev.lng()+(cur.lng()-prev.lng())/2);
			var t = new GPS_Icon();
	        t.iconSize = new GPS_Size(11, 11);
	        t.iconAnchor = new GPS_Point(5, 5);
	        t.shadow = "";
	        t.image = "images/rect.png";
	        var markerOptions = {
	            icon: t,draggable:true
	        };
	        var marker = new GPS_Marker(pos,markerOptions, g_map.map);
	        marker.prev = prev; // property only is only used in this function.
	        marker.prevIndex = i-1;
	        marker.cur = cur;
	        marker.curIndex = i;
	        g_map.addOverlay(marker);
	        marker.addListener('mouseover', function(gmk){
	        	gmk.setImage('images/rect2.png',{width:11,height:11},{x:5, y:5});
	        });
	        marker.addListener('mouseout', function(gmk){
	        	gmk.setImage('images/rect.png',{width:11,height:11},{x:5, y:5});
	        });
	        var lastDragPos = null;
	        marker.addListener('drag', function(gmk, pos){
	        	var p = gmk.prev;
	        	var c = gmk.cur;
	        	var ps = [];
	        	lastDragPos = pos;
	        	ps.push(p);
	        	ps.push(pos);
	        	ps.push(c);
	        	if(dashLine)
	        		g_map.removePolyline(dashLine);
	        	dashLine = new GPS_Polyline(ps, "#00FF00", 2);
	            g_map.addPolyline(dashLine);
	        });
	        marker.addListener('dragend', function(gmk, pos){
	        	if(dashLine)
	        		g_map.removePolyline(dashLine);
	        	var index = gmk.prevIndex + 1;
	        	geoPoints.splice(index, 0, pos);
	        	if(oldLine)
	        		g_map.removePolygon(oldLine);
	        	oldLine = new GPS_Polygon(geoPoints, "#FF0000", 3, "#00FF00", 0.3);
	            g_map.addPolygon(oldLine);
	            removeDragPoints();
	            setDragPoints(geoPoints);
	        });
	        geoMarkers.push(marker);
		}
	};
	var setDragPoints = function(points){ // set all dragging points
		for(var i=0; i < points.length; i++){ // set the corner points
			var t = new GPS_Icon();
	        t.iconSize = new GPS_Size(11, 11);
	        t.iconAnchor = new GPS_Point(5, 5);
	        t.shadow = "";
	        t.image = "images/rect.jpg";
	        var markerOptions = {
	            icon: t,draggable:true
	        };
	        var marker = new GPS_Marker(points[i],markerOptions, g_map.map);
	        g_map.addOverlay(marker);
	        marker.addListener('mouseover', function(gmk){
	        	gmk.setImage('images/rect2.jpg',{width:11,height:11},{x:5, y:5});
	        });
	        marker.addListener('mouseout', function(gmk){
	        	gmk.setImage('images/rect.jpg',{width:11,height:11},{x:5, y:5});
	        });
	        marker.addListener('drag', function(gmk, pos){ // the actual corner
	        	var oldPos = geoPoints[gmk.index];
	        	geoPoints[gmk.index] = pos;
	        	if(oldLine)
	        		g_map.removePolygon(oldLine);
	        	oldLine = new GPS_Polygon(geoPoints, "#FF0000", 3, "#00FF00", 0.3);
	            g_map.addPolygon(oldLine);
	            caculateMiddleDragPoints();
	        });
	        marker.addListener('dragend', function(gmk, pos){ // the actual
																// corner
	        	removeDragPoints();
	            setDragPoints(geoPoints);
	        });
	        
	        marker.isCorner = true;
	        marker.index = i;// property only is only used in this function.
	        geoMarkers.push(marker);
		}
		setAlphaDragPoints(points);
		
	};
	
	
	if(data_value.split(";").length > 1){
		var all = data_value.split(";");
		
        var points = [];
        
        for(var i=0; i < all.length; i++){
        	var lat = parseFloat(all[i].split(",")[1]);
    		var lng = parseFloat(all[i].split(",")[0]);
    		points.push(new GPS_LatLng(lat, lng));
        }
        
       // points.push(new GPS_LatLng(lat1, lng1));
// oldLine = new GPS_Polyline(points, "#00FF00", 2);
// g_map.addPolyline(oldLine);
        g_map.panTo(points[0]);
        oldLine = new GPS_Polygon(points, "#FF0000", 3, "#00FF00", 0.3);
        g_map.addPolygon(oldLine);
        geoPoints = points;
        if(g_map.mapProvider !='geoserver'){
        	setDragPoints(points);
        	showOKDialog();
        }else{
        	
        }
	}
	
    var h = null;
    var i = null;
    var j = null;
    var k = null;
    var l = null;
    if(g_map.mapProvider =='geoserver'){
    	geoCreated = function(){
    		if(oldLine){
    			g_map.removePolygon(oldLine);
    			oldLine = null;
    		}
    	};
    	geoDone = function(a){
    		g_map.geoPolygonControlRef.deactivate();
    		var points = a[0].getVertices(); // OpenLayers. Geometry. Point
    		var data = '';
			for(var i=0; i < points.length; i++){
				if(i > 0){
					data = data+";";
				}
				data = data + points[i].x.toFixed(6)+","+points[i].y.toFixed(6);
			}
			isDragged = false;
			isSettingAlarm = false;
			geoSelectCallBack(data);
    	};
    	g_map.geoPolygonControlRef.activate();
    	return;
	}
    if(oldLine){
    	return;
    }
    j = oldLine;
    k = g_map.addListener("click",
    function(d, e) {
        if (h == null) {
        	
            h = e;
            l = g_map.addListener("mousemove",
            function(a, b) {
                if (h != null) {
                    if (j) {
                        g_map.removePolygon(j);
                    }
                    geoPoints = [];
                    geoPoints.push(h);
                    geoPoints.push(new GPS_LatLng(h.lat(), b.lng()));
                    geoPoints.push(b);
                    geoPoints.push(new GPS_LatLng(b.lat(), h.lng()));

                    j = new GPS_Polygon(geoPoints, "#ff0000", 3, "#00FF00", 0.3, false);
                    g_map.addPolygon(j);
                    i = b;
                }
            });
        } else {

            if (k) {
                g_map.removeListener("click", k);
            }
            if (l) {
                g_map.removeListener("mousemove", l);
            }
            oldLine = j;
            setDragPoints(geoPoints);
            showOKDialog();

        }
    });
}




function locateInMap(data, callback){
	if(!data){
		return;
	}
	var latlngs = data.split(";");
	if(latlngs.length < 2){
		return;
	}
	var points = Array();
    
	for(var i=0; i < latlngs.length; i++){
		var point = latlngs[i].split(",");
		points.push(new GPS_LatLng(point[1], point[0]));
	}
	var polygon = new GPS_Polygon(points, "#ff0000", 3, "#00FF00", 0.3);
    g_map.addPolygon(polygon);
    g_map.panTo(points[0]);
    settingWin.hide();
    var win = null;
	isSettingAlarm = true; // 限定了地图不能自动移动
	isDragged = true;
    var button = new Ext.Button({type:'button', 
		text:'OK',split: false,width:100,
		enableToggle:false});
		button.on('click',function(){
			g_map.removePolygon(polygon);
			win.destroy();
			settingWin.show();
			hideElMask();
			isSettingAlarm = false; // 地图可以自动移动
			isDragged = false;
		});

	  win = new Ext.Window({html: backToGEO,closable:false,
		width:300,
        height:100,
        plain:true,
        border:false,
        buttons:[buttonno],
        bodyCssClass:'gps-window-body',
        x:150,
        y:100,
        modal:false
		});
	win.show();
	showElMask();
}

var elMask = null;
function showElMask(){
	if(elMask == null){
		elMask = document.createElement("div");
		elMask.style.width = '100%';
		elMask.style.height = '100%';
		elMask.style.opacity = 0;
		elMask.style.filter = 'alpha(opacity=0)';
		elMask.style.position = 'absolute';
		elMask.style.left = '0px';
		elMask.style.top = '0px';
		elMask.style.zIndex = 500;
		Ext.getBody().appendChild(elMask);
	}
	elMask.style.display = '';
}

function hideElMask(){
	if(elMask)
		elMask.style.display = 'none';
}